package com.example.demo.service;

import com.example.demo.entity.ads;
import com.example.demo.repository.AdsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;

@Service
public class AdsService {
    @Autowired
    private AdsRepository adsRepository;

    public Iterable<ads> getAllAds(){
        return adsRepository.findAll();
    }

    public ads getAdsById(int id) {
        return adsRepository.findById(id).get();
    }

    public ArrayList<ads> getAdsByUTime(Iterable<ads> advertises){
        Iterator it=advertises.iterator();
        ArrayList<ads> list=new ArrayList<>();
        while(it.hasNext()){
            list.add((ads) it.next());
        }
        list.sort(new Comparator<ads>() {
            @Override
            public int compare(ads o1, ads o2) {
                if(o1.getUpdate_time().before(o2.getUpdate_time())){
                    return 1;
                }
                else return -1;
            }
        });
        return list;
    }

    public ArrayList<ads> getAdsByCTime(Iterable<ads> allAds) {
        Iterator it=allAds.iterator();
        ArrayList<ads> list=new ArrayList<>();
        while(it.hasNext()){
            list.add((ads) it.next());
        }
        list.sort(new Comparator<ads>() {
            @Override
            public int compare(ads o1, ads o2) {
                if(o1.getCreate_time().before(o2.getCreate_time())){
                    return 1;
                }
                else return -1;
            }
        });
        return list;
    }

    public String addAds(int id) {
        ads a=new ads();
        a.setContent("new ads!!!");
        a.setId(id);
        adsRepository.save(a);
        return "Saved!";
    }

    public String addAds(int id,String content){
        ads a=new ads();
        a.setContent(content);
        a.setId(id);
        adsRepository.save(a);
        return "Saved!!!";
    }

    public String deleteAds(int id) {
        adsRepository.deleteById(id);
        return "Delete "+id+" ad!!!";
    }

    public String updateAds(int id, String content) {
        ads a=adsRepository.findById(id).get();
        a.setContent(content);
        adsRepository.save(a);
        return "Updated!!!";
    }


}
